﻿//-----------------------------------------------------------------------
// <copyright file="CommonPlaceDetailPage.xaml.cs" company="FIT VUT">
//     Copyright (c) FIT VUT. All rights are reserved.
// </copyright>
//----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Resources;
using System.Windows.Shapes;
using BookCaching.Settings;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace BookCaching.Pages
{
    /// <summary>
    /// Page displays information about a specific place.
    /// </summary>
    public partial class CommonPlaceDetailPage : PhoneApplicationPage
    {
        private BookCaching.Knihotoc_WCFService.Place place;
        private int loadedThings;
        private const int thingsNeededToLoad = 1;

        public CommonPlaceDetailPage()
        {
            this.InitializeComponent();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            loadedThings = 0;
            base.OnNavigatedTo(e);

            if (NavigationContext.QueryString.ContainsKey("PlaceID"))
            {
                Knihotoc_WCFService.Knihotoc_WP7ServiceClient client = new Knihotoc_WCFService.Knihotoc_WP7ServiceClient();
                client.GetPlaceByIdCompleted += Knihotoc_WP7ServiceClient_GetPlaceByIdCompleted;
                client.GetPlaceByIdAsync(int.Parse(NavigationContext.QueryString["PlaceID"]));                
            }

            (ApplicationBar.Buttons[0] as ApplicationBarIconButton).Text = Localization.LocalizedStrings.Get("ShowOnMapButton");
            ApplicationBar.BackgroundColor = CurrentSettings.Instance.ForegroundColor.Color;
        }

        void Knihotoc_WP7ServiceClient_GetPlaceByIdCompleted(object sender, Knihotoc_WCFService.GetPlaceByIdCompletedEventArgs e)
        {
            try
            {
                if (e != null && e.Result != null)
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        this.place = e.Result;

                        commonPlaceNameText.Text = this.place.Name;
                        this.infoText.Text = this.place.Description;

                        StreamResourceInfo sr = Application.GetResourceStream(new Uri("Images/NoImage.jpg", UriKind.Relative));
                        if (this.place.ImageUrl.Length > 0)
                        {
                            BitmapImage imageOnline = new BitmapImage(new Uri(this.place.ImageUrl));
                            imageOnline.ImageFailed += new EventHandler<ExceptionRoutedEventArgs>(ImageOnline_ImageFailed);
                            this.logoImage.Source = imageOnline;
                        }
                        else
                        {
                            this.LogoImage_LoadNoImage();
                        }

                        this.addressText.Text = this.place.Address.Street + " " + this.place.Address.StreetNumber + "\n"
                                                + this.place.Address.City;
                    });
                }
            }
            finally
            {
                loadedThings++;
                if (loadedThings == thingsNeededToLoad)
                {
                    ((Knihotoc_WCFService.Knihotoc_WP7ServiceClient)sender).CloseAsync();
                }
            }
        }

        private void ImageOnline_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {
            try
            {
                BitmapImage imageLocal = new BitmapImage();
                string path = this.place.ImageUrl.Substring(1, this.place.ImageUrl.Length - 1);
                StreamResourceInfo sr = Application.GetResourceStream(new Uri(path, UriKind.Relative));
                imageLocal.SetSource(sr.Stream);
                this.logoImage.Source = imageLocal;
            }
            catch (Exception)
            {
                this.LogoImage_LoadNoImage();
            }
        }

        private void LogoImage_LoadNoImage()
        {
            StreamResourceInfo sr = Application.GetResourceStream(new Uri("Images/NoImage.jpg", UriKind.Relative));
            BitmapImage imageNoImage = new BitmapImage();
            imageNoImage.SetSource(sr.Stream);
            this.logoImage.Source = imageNoImage;
        }

        private void LogoImage_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {            
        }

        private void ShowOnMapButton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri(String.Format("/Pages/MapPage.xaml?Latitude={0}&Longitude={1}", place.Address.Lat.ToString(), place.Address.Lon.ToString()), UriKind.Relative));
        }
    }
}